var stompClient = null;
//设置连接状态控制显示隐藏
function setConnected(connected) {
	$("#connect").attr("disabled", connected);
	$("#disconnect").attr("disabled", !connected);
	if (!connected) {
		$("#inputDiv").hide();
	} else {
		$("#inputDiv").show();
	}

}
//连接
function connect() {
	var socket = new SockJS("/webSocket/webSocketEndPoint");  // 建立连接对象（还未发起连接）
	stompClient = Stomp.over(socket);   // 获取 STOMP 子协议的客户端对象
	
	// 向服务器发起websocket连接并发送CONNECT帧
	stompClient.connect({}, function(frame) {
		setConnected(true);
		console.log("connected : " + frame);
		 
		stompClient.subscribe('/user/' + "zs2"+ '/demo3/greetings', function(greeting) {
			showGreeting(JSON.parse(greeting.body).userId, JSON
					.parse(greeting.body).content);
		});
		
		
		
	})
	var storage = window.localStorage;
	var Who = document.getElementById("who");
	var myname = storage.getItem("username");
	Who.innerHTML = "<option value=" + myname + "> " + myname + " 说:</option>";
	setMessageInnerHTML("连接成功");

}
//断开连接
function disconnect() {
	if (stompClient != null) {
		stompClient.disconnect();
	}
	setConnected(false);
	console.log("disconnected!");
	setMessageInnerHTML("连接断开");
}

//发送名称到后台
function sendName() {
	
	
	//stompClient.send("/queue/test", {priority: 9}, "Hello, STOMP");
	
	
	var message = $("#talkwords").val();
	
	alert("message"+message);
	
	stompClient.send("/user/demo1", {}, JSON.stringify({
		'message' : message,
		'username':'zs1'
	}));
	
	var storage = window.localStorage;
	var Words = document.getElementById("words");
	var Who = document.getElementById("who");
	var TalkWords = document.getElementById("talkwords");
	var TalkSub = document.getElementById("talksub");

	var myname = storage.getItem("username");
	var str = "";
	var msg = TalkWords.value;
	// 消息为空时弹窗
	if (TalkWords.value == "") {
		return;
	}
	str = '<div class="btalk"><span>' + myname + '说 :' + msg + '</span></div>';
	// window.location.href="http://localhost:8080/first/index.html";
	Words.innerHTML = Words.innerHTML + str;

}

//将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
	document.getElementById('message').innerHTML += innerHTML + '<br/>';
}

//订阅消息
function subscribe3() {
    stompClient.subscribe('/api/v1/socket/req/message', function (response) {
    	console.log("我接收到消息了。。在这儿。。");
        var returnData = JSON.parse(response.body);
        console.log("123321");
        setMessageInnerHTML("/api/v1/socket/req/message 你接收到的消息为:" + returnData.responseMessage);
    });
}




